# encoding='utf-8'
"""
@Author: 张晟烨
@Date: 2022/12/03
@Email: zhangsy@zylliondata.com
@Description:  Mongo最简单的增删改查
@Version: Python3.8
@Modified By: 

"""
from pymongo import MongoClient


class MongoContext:

    """
    Mongo最简单的增删改查
    """
    def __init__(self, rw='r', db='cpt') -> None:
        user = 'myuser'
        pwd = '123'
        host = '42.192.14.215'
        # self.uri="mongodb://%s:%s@%s" % (quote_plus(user), quote_plus(pwd), host)
        # db 指定要连接的数据库，
        # user/pwd指定数据库的用户密码
        self.client = MongoClient(host=host, port=27017, username=user, password=pwd, authSource=db)
        # conn = MongoClient('mongodb://{}:{}@{}:{}/?authSource={}'.format(user,pwd,host,27017,db))
        self.db = self.client[db]

    def __enter__(self):

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.client.close()


if __name__ == '__main__':
    # 学生们在
    with MongoContext('r', 'cpt') as mongo:
        for n in range(1, 200):
            # 增
            stu = mongo.db['test_zsy'].insert({"Name": n})
            print(str(stu))
            # 删
            # mongo.db['lihs'].remove({'Name':"2"})
            # # 改
            # mongo.db['lihs'].update_one({'Name':'2'},{"$set": dict({"Gender": 'male'})}, True)
            # # 查
            # mongo.db['lihs'].find({"Name": n})
